using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PasteFormHelper;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace OpenPasteSpider.projectmodel
{

    /// <summary>
    /// 服务器信息
    ///</summary>
    public class LinuxInfoAppService : OpenPasteSpiderAppService
    {

        private IOpenPasteSpiderDbContext _dbContext;
        private readonly PublicModelHelper _modelHelper;
        private readonly ChannelHelper _slaveChannelHelper;

        //private readonly LinkHelper _linkHelper;

        public LinuxInfoAppService(IOpenPasteSpiderDbContext dbContext, PublicModelHelper modelHelper, ChannelHelper slaveChannelHelper)
        {
            _dbContext = dbContext;
            _modelHelper = modelHelper;
            _slaveChannelHelper = slaveChannelHelper;
            //_linkHelper = linkHelper;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<PagedResultDto<LinuxInfoListDto>> GetListAsync(int page = 1, int size = 20)
        {

            var query = _dbContext.LinuxInfo.Where(t => 1 == 1)
            .OrderByDescending(xy => xy.Id);

            var pagedResultDto = new PagedResultDto<LinuxInfoListDto>();
            pagedResultDto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).ToListAsync();
            var temList = ObjectMapper.Map<List<LinuxInfo>, List<LinuxInfoListDto>>(userList);
            pagedResultDto.Items = temList;
            return pagedResultDto;
        }

        /// <summary>
        /// 根据ID获取单项服务器信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        public LinuxInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.LinuxInfo.Where(t => t.Id == id)
            .FirstOrDefault();
            var temList = ObjectMapper.Map<LinuxInfo, LinuxInfoDto>(query);
            temList.SSHPass = "";
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息服务器信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        public LinuxInfoDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.LinuxInfo.Where(t => t.Id == id).AsNoTracking().FirstOrDefault();
            var temList = ObjectMapper.Map<LinuxInfo, LinuxInfoDto>(query);
            temList.SSHPass = "";
            return temList;
        }


        /// <summary>
        /// 添加一个服务器信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        public async Task<LinuxInfoDto> CreateItemAsync(LinuxInfoAddDto input)
        {

            var newu = ObjectMapper.Map<LinuxInfoAddDto, LinuxInfo>(input);
            newu.IsEnable = true;            //添加自定义
            newu.SlaveName = "";//设置为空，需要的时候会进行分配和赋值的
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            //var updated = await _repository.InsertAsync(newu,true);
            var backinfo = ObjectMapper.Map<LinuxInfo, LinuxInfoDto>(newu);
            _slaveChannelHelper.WriteSlaveAction(new SlaveEventModel() { Event = SlaveEventCode.linuxadd, Object=Newtonsoft.Json.JsonConvert.SerializeObject(backinfo) });
            return backinfo;
        }
        /// <summary>
        /// 更新一个服务器信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
        public async Task<LinuxInfoDto> UpdateItemAsync(LinuxInfoUpdateDto input)
        {
            var info = await _dbContext.LinuxInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }

            var oldpass = info.SSHPass;
            ObjectMapper.Map<LinuxInfoUpdateDto, LinuxInfo>(input, info);
            if (!String.IsNullOrEmpty(input.SSHPass))
            {
                info.SSHPass = input.SSHPass;
            }
            else
            {
                info.SSHPass = oldpass;
            }
            //var updated = await _repository.UpdateAsync(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<LinuxInfo, LinuxInfoDto>(info);
            await _modelHelper.ItemLinuxClean(input.Id);

            if (input.IsEnable)
            {
                _slaveChannelHelper.WriteSlaveAction(new SlaveEventModel() { Event = SlaveEventCode.linuxupdate,Object=Newtonsoft.Json.JsonConvert.SerializeObject(backinfo) });
            }
            else
            {
                _slaveChannelHelper.WriteSlaveAction(new SlaveEventModel() { Event = SlaveEventCode.linuxremove, Object = Newtonsoft.Json.JsonConvert.SerializeObject(backinfo) });
            }



            return backinfo;
        }
        
        /// <summary>
        /// 读取AddDto的数据模型 用于新增
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadAddModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<LinuxInfoAddDto>(new LinuxInfoAddDto());
            return _model;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于更新
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadUpdateModel(int id)
        {
            var _info = await _dbContext.LinuxInfo.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<LinuxInfo, LinuxInfoUpdateDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<LinuxInfoUpdateDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于查看详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadDetailModel(int id)
        {
            var _info = await _dbContext.LinuxInfo.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<LinuxInfo, LinuxInfoDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<LinuxInfoDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取ListDto的数据模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadListModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<LinuxInfoListDto>(new LinuxInfoListDto());
            var _query_model = PasteBuilderHelper.ReadModelProperty(new InputSearchBase());
            if (_query_model != null)
            {
                _model.QueryProperties = _query_model.Properties;
            }
            return _model;
        }

        /// <summary>
        /// 按页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<PagedResultDto<LinuxInfoListDto>> Page([FromQuery]InputSearchBase input)
        {
            var query = _dbContext.LinuxInfo.Where(t => 1 == 1).OrderByDescending(x=>x.Id);
            var _pagedto = new PagedResultDto<LinuxInfoListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(input.page, input.size).ToListAsync();
            var temList = ObjectMapper.Map<List<LinuxInfo>, List<LinuxInfoListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }    }
}
